﻿#include "logindialog.h"
#include "ui_logindialog.h"

LoginDialog::LoginDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::LoginDialog)
{
    ui->setupUi(this);

    //setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
    setWindowFlags(Qt::WindowMinimizeButtonHint | Qt::WindowCloseButtonHint);

    ui->m_userName->addAction(QIcon(":/images/user.png"), QLineEdit::LeadingPosition);
    ui->m_pwd->addAction(QIcon(":/images/lock.png"), QLineEdit::LeadingPosition);

    connect(ui->m_btnLogin, &QPushButton::clicked, this, &LoginDialog::on_login);
    connect(ui->m_btnCancel, &QPushButton::clicked, this, &LoginDialog::on_cancel);
}

LoginDialog::~LoginDialog()
{
    delete ui;
}

void LoginDialog::on_login()
{
    if(ui->m_userName->text().length() <= 0)
    {
        QMessageBox::information(this,
                                 QString::fromLocal8Bit("提示"),
                                 QString::fromLocal8Bit("请输入用户名"));
        return;
    }
    if(ui->m_pwd->text().length() <= 0)
    {
        QMessageBox::information(this,
                                 QString::fromLocal8Bit("提示"),
                                 QString::fromLocal8Bit("请输入密码"));
        return;
    }

    QSqlDatabase database = QSqlDatabase::database(DbUtil::SQLITE_CONNECTION_NAME, true);
    if(database.isOpen())
    {
        qDebug() << "open";

        QSqlQuery sql_query(database);
        QString sql = QString("select count(user_id) from t_user where user_name = '%1'")
                .arg(ui->m_userName->text());
        qDebug() << sql;
        if(!sql_query.exec(sql))
        {
            qDebug() << sql_query.lastError().text();
        }
        else
        {
            sql_query.next();
            if(sql_query.value(0).toInt() != 1)
            {
                QMessageBox::information(this,
                                         QString::fromLocal8Bit("提示"),
                                         QString::fromLocal8Bit("用户异常"));
                return;
            }
        }

        sql = QString("select pwd from t_user where user_name = '%1'")
                .arg(ui->m_userName->text());
        qDebug() << sql;
        if(!sql_query.exec(sql))
        {
            qDebug() << sql_query.lastError().text();
        }
        else
        {
            sql_query.next();
            if(ui->m_pwd->text() != sql_query.value(0).toString())
            {
                QMessageBox::information(this,
                                         QString::fromLocal8Bit("提示"),
                                         QString::fromLocal8Bit("密码错误"));
                return;
            }
        }
    }
    accept();
}

void LoginDialog::on_cancel()
{
    reject();
}
